package wallet

import (
	"context"
	"net/http"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"gitee.com/enjoy_5/enjoy-wallet/internal/server"
	wallet2 "gitee.com/enjoy_5/enjoy-wallet/model/wallet"
	wallet "gitee.com/enjoy_5/enjoy-wallet/proto/wallet"
)

type WalletService struct {
	wallet.UnimplementedWalletServer
}

func (s *WalletService) CreateRechargeRecord(ctx context.Context, in *wallet.CreateRechargeRecordRequest) (*wallet.CreateRechargeRecordResponse, error) {
	if in.GetIn().GetUserid() == 0 {
		return nil, status.Errorf(http.StatusInternalServerError, "id is required")
	}
	info, err := server.CreateAmount(in.GetIn())
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}
	return &wallet.CreateRechargeRecordResponse{
		RechargeRecordDescription: info,
	}, nil

}

func (s *WalletService) FirstUserBalance(ctx context.Context, in *wallet.FirstUserBalanceRequest) (*wallet.FirstUserBalanceResponse, error) {
	if in.GetIn().GetUserid() == 0 {
		return nil, status.Errorf(http.StatusInternalServerError, "id is required")
	}

	info, err := server.FirstUserBalance(in.GetIn().GetUserid())
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	return &wallet.FirstUserBalanceResponse{
		UserBalanceInfo: info,
	}, nil
}

func (s *WalletService) CreateUserConsumptionDetails(ctx context.Context, in *wallet.CreateUserConsumptionDetailsRequest) (*wallet.CreateUserConsumptionDetailsResponse, error) {
	if in.GetIn().GetUserid() == 0 {
		return nil, status.Errorf(http.StatusInternalServerError, "id is required")
	}

	info, err := server.CreateConsumption(in.GetIn())
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	return &wallet.CreateUserConsumptionDetailsResponse{
		UserConsumptionDetailsInfo: info,
	}, nil
}

func (s *WalletService) SearchUserConsumptionDetails(ctx context.Context, in *wallet.SearchUserConsumptionDetailsRequest) (*wallet.SearchUserConsumptionDetailsResponse, error) {
	if in.Limit > 10000 {
		return nil, status.Errorf(http.StatusInternalServerError, "查询数据必须小于10000条", nil)
	}

	limit, offset, err := wallet2.SearchConsumption(int(in.Offset), int(in.Limit))
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	var info []*wallet.UserConsumptionDetailsInfo

	for _, v := range limit {
		info = append(info, &wallet.UserConsumptionDetailsInfo{
			Userid:          v.UserID,
			TransactionType: v.TransactionType,
			Amount:          v.Amount,
			Balance:         v.Balance,
			Description:     v.Description,
		})
	}

	return &wallet.SearchUserConsumptionDetailsResponse{
		Infos: info,
		Total: offset,
	}, nil
}
